package com.qingmi.farmer.ui.my;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;

import com.blankj.utilcode.util.CleanUtils;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qingmi.farmer.BuildConfig;
import com.qingmi.farmer.R;
import com.qingmi.farmer.data.UserData;
import com.qingmi.farmer.data.model.UpdateVersion;
import com.qingmi.farmer.data.repository.data.BasicDataRepository;
import com.qingmi.farmer.data.repository.data.UserDataRepository;
import com.qingmi.farmer.databinding.FragmentMineBinding;
import com.qingmi.farmer.event.UserDataChangeEvent;
import com.qingmi.farmer.event.UserLoginChangeEvent;
import com.qingmi.farmer.ui.login.LoginActivity;
import com.qingmi.farmer.window.UpdateVersionDialog;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.wjjun.base.data.preference.UserPreference;
import com.wjjun.base.ui.base.BaseFragment;
import com.wjjun.base.ui.window.AlertDialog;
import com.wjjun.basemvpvm.data.exception.MyException;
import com.wjjun.basemvpvm.data.observer.DefaultObserver;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 我的
 * Created by 67535 on 2018/4/28.
 */

public class MineFragment extends BaseFragment<MineViewModel, FragmentMineBinding> {

    @Inject
    BasicDataRepository basicDataRepository;

    @Inject
    UserData userData;

    @Inject
    UserPreference userPreference;

    @Inject
    UserDataRepository userDataRepository;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected MineViewModel initViewModel() {
        return new MineViewModel();
    }

    @Override
    protected void initContent() {
        super.initContent();

        RxBus.getDefault().register(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        initUserData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserDataChange(UserDataChangeEvent event) {
        initUserData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUserLoginChange(UserLoginChangeEvent event) {
        initUserData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initUserData();
        }
    }

    private void initUserData() {
        if (userData.isLogin()) {
            viewModel.headUrl.set(userData.getAvatar());
            viewModel.nick.set(userData.getUserName());
            viewModel.phone.set(userData.getPhone());
        } else {
            viewModel.headUrl.set("");
            viewModel.nick.set(getString(R.string.hint_login));
            viewModel.phone.set("");
        }

        viewModel.msgCount.set(userData.getTotalUnReadMsgCount());
        viewModel.versionName.set(BuildConfig.VERSION_NAME);
        viewModel.hasNewVersion.set(BuildConfig.VERSION_CODE < userPreference.getIgnoreVersion());
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (getActivity() == null) {
            showToast(R.string.error_activity_is_null);
            return;
        }
        switch (view.getId()) {
            case R.id.iv_setting:// 设置
                break;
            case R.id.rl_info:  //用户信息
                LoginActivity.start(getActivity());
                break;
            case R.id.ly_my_cooperative:// 我的合作社
                break;
            case R.id.tv_receive_address:   //常用收货地址
                break;
            case R.id.ly_bill:// 账单
                break;
            case R.id.ly_residual:// 余额
                break;
            case R.id.ly_bank_card:// 银行卡
                break;
            case R.id.ly_my_alipay:// 我的支付宝
                break;
            case R.id.ly_about_us:// 关于我们
                break;
            case R.id.ly_clear_cache:// 清除缓存
                requestPermissions();
                break;
            case R.id.ly_now_version:// 当前版本
                updateVersion();
                break;
        }
    }

    @SuppressLint("CheckResult")
    private void requestPermissions() {
        if (getRxPermissions() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                getRxPermissions().request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean granted) throws Exception {
                                if (granted) {
                                    clearCache();
                                } else {
                                    AlertDialog alertDialog = new AlertDialog(getActivity());
                                    alertDialog.setTitleByRes(R.string.error_permission);
                                    alertDialog.show();
                                }
                            }
                        });
            }
        } else {
            clearCache();
        }
    }

    private void clearCache() {
        //延迟1秒
        Observable.timer(1, TimeUnit.SECONDS)
                .compose(bindUntilEvent(FragmentEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoadingDialog(R.string.loading_clear_cache);
                    }

                    @Override
                    public void onNext(Object o) {
                        if (getActivity() != null) {
                            PictureFileUtils.deleteCacheDirFile(getActivity());
                            PictureFileUtils.deleteExternalCacheDirFile(getActivity());
                        }
                        //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
                        CleanUtils.cleanInternalCache();
                        CleanUtils.cleanExternalCache();
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                        showToast(R.string.error_clear_cache);
                    }
                });
    }

    private void updateVersion() {
        showLoadingDialog(R.string.loading_update);
        basicDataRepository.updateVersion(new DefaultObserver<UpdateVersion>() {
            @Override
            public void onNext(UpdateVersion updateVersion) {
                dismissLoadingDialog();
                if (getActivity() == null) {
                    showToast(R.string.error_activity_is_null);
                    return;
                }
                if (updateVersion == null) {
                    showToast(R.string.prompt_no_new_version);
                    return;
                }
                if (BuildConfig.VERSION_CODE >= updateVersion.getNowVerNo()) {  //已经是最新版本
                    showToast(R.string.prompt_no_new_version);
                } else {
                    new UpdateVersionDialog(getActivity(), userPreference, updateVersion).show();
                }
            }

            @Override
            public void onError(MyException e) {
                dismissLoadingDialog();
                showToast(e.getMessage());
            }
        });
    }
}
